﻿Imports Telerik.Web.UI
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO

Partial Class VoucherDtl
    Inherits System.Web.UI.Page
    Dim _CommandName As String
    Dim _Command As String
    Dim Grid As RadGrid
    Dim VoucherObj As New DBVoucherSP
    Dim VoucherDS As New Data.DataSet
    Dim VoucherLinesObj As New DBVoucherLinesSP
    Dim VoucherLinesDS As New Data.DataSet
    Dim AccountObj As New AccountsSP
    Dim AccountDataSet As New DataSet
    Dim FilesObj As New DBtblFilesSP
    Dim FilesDatatset As New Data.DataSet
    Public strConnection As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString.ToString
    Dim index As Integer = -1

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Me.Theme = GetGlobalResourceObject("SystemResource", "Theme")
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim _lblPageTitle As Label
            _lblPageTitle = Me.Master.FindControl("lblPageTitle")
            _lblPageTitle.Text = GetLocalResourceObject("PageTitle")
            rdpDate.DbSelectedDate = DateTime.Now()
            rtbYear.Text = Year(Now()).ToString()

            hdnVoucherID.Value = Request.QueryString("VoucherID").ToString

            If hdnVoucherID.Value <> "" Then
                FillVoucherDtl()
            Else
                hdnVoucherID.Value = "-1"
                rdpDate.DbSelectedDate = Now    'Default Document Date is Today
                rtbYear.Text = Year(Now()).ToString()         'Default Year is the Current Year
            End If
            btnCancel.Attributes.Add("onClick", "javascript:history.back(); return false;")

        End If
    End Sub

   

#Region "Attachments"


    Private Sub UploadAttachments()

        Dim FileUpload As RadAsyncUpload = AsyncUploadVoucher

        lblUploadError.Visible = False
        If Not (FileUpload.UploadedFiles.Count > 0) Then
            'CType(Form.FindControl("lblUploadError"), Label).Visible = False
            'lblUploadError.Visible = False
            Return
        End If

        For i As Integer = 0 To FileUpload.UploadedFiles.Count - 1


            Dim fs As System.IO.Stream = FileUpload.UploadedFiles(i).InputStream

            Dim imageBytes As [Byte]() = New [Byte](fs.Length - 1) {}
            fs.Read(imageBytes, 0, CInt(fs.Length))
            fs.Close()



            'FilesDatatset = FilesObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "RtvFile", , , CType(Form.FindControl("hdnVoucherID"), HiddenField).Value.ToString(), , , )
            Dim strQuery As [String]

            'If FilesDatatset.Tables(0).Rows.Count > 0 Then
            'insert the file into database
            'FilesDatatset = FilesObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "SaveFile", , , , , , )
            'strQuery = "Update tblFiles set [Name] = @Name, [ContentType] = @ContentType , [Data] = @Data where [Voucher_IDC] = @Voucher_IDC and [Voucher_IDN] = @Voucher_IDN "
            'Else
            'insert the file into database
            strQuery = "insert into tblFiles([Voucher_IDC], [Voucher_IDN],[Name], [ContentType], [Data]) values (@Voucher_IDC, @Voucher_IDN,@Name, @ContentType, @Data)"
            'End If


            Dim cmd As New SqlCommand(strQuery)
            cmd.Parameters.AddWithValue("@Voucher_IDC", "V")
            cmd.Parameters.AddWithValue("@Voucher_IDN", hdnVoucherID.Value.ToString())
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = FileUpload.UploadedFiles(i).GetName()

            'Make sure we are dealing with a Compatible File Format Like JPG or GIF file
            Dim extension As String = System.IO.Path.GetExtension(FileUpload.UploadedFiles(i).GetName()).ToLower()
            Dim MIMEType As String = Nothing
            Select Case extension
                Case ".gif"
                    MIMEType = "image/gif"
                    Exit Select
                Case ".jpg", ".jpeg", ".jpe"
                    MIMEType = "image/jpeg"
                    Exit Select
                Case ".png"
                    MIMEType = "image/png"
                    Exit Select
                Case ".bmp"
                    MIMEType = "image/bmp"
                    Exit Select
                Case ".txt"
                    MIMEType = "application/txt"
                    Exit Select
                Case ".pdf"
                    MIMEType = "application/pdf"
                    Exit Select
                Case ".doc"
                    MIMEType = "application/msword"
                    Exit Select
                Case ".xls"
                    MIMEType = "application/msexcel"
                    Exit Select
                Case ".docx"
                    MIMEType = "application/vnd.ms-word"
                    Exit Select
                Case ".xlsx"
                    MIMEType = "application/vnd.ms-excel"
                    Exit Select
                Case Else
                    '   Invalid file type uploaded
                    'CType(Form.FindControl("lblUploadError"), Label).Visible = True
                    lblUploadError.Visible = True
                    Return
            End Select

            cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = MIMEType
            cmd.Parameters.Add("@Data", SqlDbType.VarBinary).Value = imageBytes
            ' bytes;
            InsertUpdateData(cmd)

        Next

    End Sub

    Private Function InsertUpdateData(ByVal cmd As SqlCommand) As [Boolean]
        Dim con As New SqlConnection(strConnection)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
            Return True
        Catch ex As Exception
            Response.Write(ex.Message)
            Return False
        Finally
            con.Close()
            con.Dispose()
        End Try
    End Function


#End Region


    Sub SaveControls()
        hdnVoucherID.Value = VoucherObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteScalar, "SaveVoucher", _
                                                      hdnVoucherID.Value, rtbYear.Text, rtbVoucherNo.Text, rdpDate.DbSelectedDate, rcbType.SelectedValue, _
                                                      rcbMainCostCenter.SelectedValue, rcbCostCenter.SelectedValue, , rtbRemarks.Text)
        SaveDtl()
        UploadAttachments()
    End Sub

    Protected Sub SaveDtl()
        Dim regDate As Date = Date.Now()
        Dim strDate As String = regDate.ToString("ddMMMyyyy")

        For counter = 0 To rgVoucherLines.Items.Count - 1
            VoucherLinesObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "SaveVoucherLine", rgVoucherLines.Items(counter)("ID").Text, _
            hdnVoucherID.Value, _
            IIf(rgVoucherLines.Items(counter)("TransYear").Text = "&nbsp;", "", rgVoucherLines.Items(counter)("TransYear").Text), _
            IIf(rgVoucherLines.Items(counter)("PayOrderNo").Text = "&nbsp;", "", rgVoucherLines.Items(counter)("PayOrderNo").Text), _
             IIf(rgVoucherLines.Items(counter)("ProgramNo").Text = "&nbsp;", "", rgVoucherLines.Items(counter)("ProgramNo").Text), _
             IIf(rgVoucherLines.Items(counter)("AccountNo").Text = "&nbsp;", "", rgVoucherLines.Items(counter)("AccountNo").Text), _
             IIf(rgVoucherLines.Items(counter)("CostCenterNo").Text = "&nbsp;", "", rgVoucherLines.Items(counter)("CostCenterNo").Text), _
             IIf(rgVoucherLines.Items(counter)("Debit").Text = "&nbsp;", "", rgVoucherLines.Items(counter)("Debit").Text), _
             IIf(rgVoucherLines.Items(counter)("Credit").Text = "&nbsp;", "", rgVoucherLines.Items(counter)("Credit").Text), _
            CType(rgVoucherLines.Items(counter)("RecordStatus").Controls(0), HyperLink).Text, _
            Session("UserName").ToString(), Now, _
             IIf(rgVoucherLines.Items(counter)("Remarks").Text = "&nbsp;", "", rgVoucherLines.Items(counter)("Remarks").Text))
        Next
    End Sub

    Sub DeleteRecord()
        VoucherDS = VoucherObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "DeleteVoucher", hdnVoucherID.Value)
    End Sub

    Protected Sub FillVoucherDtl()
        VoucherDS = VoucherObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "RtvVoucherByID", hdnVoucherID.Value)
        If VoucherDS IsNot Nothing Then
            If VoucherDS.Tables(0).Rows.Count > 0 Then

                rtbYear.Text = VoucherDS.Tables(0).Rows(0).Item("Year").ToString()
                rtbVoucherNo.Text = VoucherDS.Tables(0).Rows(0).Item("VoucherNo").ToString()
                rdpDate.DbSelectedDate = VoucherDS.Tables(0).Rows(0).Item("VoucherDate").ToString()
                rcbType.DataBind()
                rcbType.SelectedValue = VoucherDS.Tables(0).Rows(0).Item("VoucherType").ToString()
                rcbMainCostCenter.DataBind()
                rcbMainCostCenter.SelectedValue = VoucherDS.Tables(0).Rows(0).Item("MainCostCenter").ToString()
                rcbCostCenter.DataBind()
                rcbCostCenter.SelectedValue = VoucherDS.Tables(0).Rows(0).Item("CostCenter").ToString()
                hdnRecordStatus.Value = VoucherDS.Tables(0).Rows(0).Item("RecordStatus").ToString()
                rtbRemarks.Text = VoucherDS.Tables(0).Rows(0).Item("Remarks").ToString()

                If hdnRecordStatus.Value = "2" Then 'Voucher is exported so fields disabled
                    rtbYear.Enabled = False
                End If
            End If
        End If
    End Sub


    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            If rcbType.SelectedIndex = 0 Then
                Label2.Visible = True
                Exit Sub
            Else
                SaveControls()
                CleanTemp() ' This Function is to Clean The Temporary Files Stored by RadAsyncUpload in App_Data\RadUploadTemp
                RadAjaxManager1.ResponseScripts.Add("radalert('Information Saved Successfully !', 270, 100);")
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect("~/VoucherHdr.aspx")
    End Sub

    Sub CleanTemp()
        Dim dir As New DirectoryInfo(Server.MapPath("~\App_Data\RadUploadTemp"))
        Dim file As IO.FileInfo() = dir.GetFiles()
        For i = 0 To file.Length - 1
            file(i).Delete()
        Next
    End Sub
    Protected Sub rgVoucherLines_ItemCommand(ByVal source As Object, ByVal e As GridCommandEventArgs) Handles rgVoucherLines.ItemCommand
        _CommandName = e.CommandName
    End Sub

    Protected Sub rgVoucherLines_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles rgVoucherLines.ItemDataBound
        If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) And _CommandName <> "InitInsert" Then
            'If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) Then

            Dim editFormItem As GridEditFormItem = CType(e.Item, GridEditFormItem)
            Dim parentItem As GridDataItem = editFormItem.ParentItem

            Dim box As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbv"), RadComboBox)
            box.SelectedValue = parentItem("AccountNo").Text
            Dim box1 As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbd"), RadComboBox)
            box1.SelectedValue = parentItem("AccountNo").Text

            Dim box2 As RadComboBox = CType(editFormItem.FindControl("WUCCostCenter").FindControl("rcbd"), RadComboBox)
            box2.SelectedValue = parentItem("CostCenterNo").Text
        End If

    End Sub
End Class

